<?php

namespace app\common\service;

use app\common\exception\BackErrorException;
use app\common\model\Recommend as RecommendModel;
use think\Collection;
use think\facade\Db;
use app\wxapp\service\WechatUserService as WxappWechatUserService;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/4 0004
 * Time: 22:27
 */
class RecommendService extends BaseServices
{

    private $searchVideo = 1;
    private $searchTopic = 2;

    /**
     * 根据用户的设置取推荐
     * @param $userId
     * @param $page
     * @return array
     */
    public function recommend($userId, $page)
    {
//        $userService = new WxappWechatUserService();
//        $cateIds = $userService->getSelectedCategory($userId);
        //暂时只取这么多
//        $recommends = Db::table("recommend")->whereIn("category_id", $cateIds)->page($page, 20)->select()->toArray();
        $recommends = Db::table("recommend")->order('update_time', 'desc')->page($page, 20)->select()->toArray();
        $videoIds = [];
        $topicIds = [];
        foreach ($recommends as $key => $val) {
            if ($val['type'] == RecommendModel::TYPE_VIDEO) {
                array_push($videoIds, $val['src_id']);
            } else if ($val['type'] == RecommendModel::TYPE_TOPIC) {
                array_push($topicIds, $val['src_id']);
            }
        }

        $videos = Db::table("video_list")->whereIn("id", $videoIds)->column("id,title,out_video_id,cover_url,duration,hot", "id");
        $topics = Db::table("topic")->whereIn("id", $topicIds)->column("id,title,cover_url,hot", "id");


        foreach ($recommends as $key => $val) {
            if ($val['type'] == RecommendModel::TYPE_VIDEO) {
                $recommends[$key]['data'] = isset($videos[$val['src_id']]) ? $videos[$val['src_id']] : [];
            } else if ($val['type'] == RecommendModel::TYPE_TOPIC) {
                $recommends[$key]['data'] = isset($topics[$val['src_id']]) ? $topics[$val['src_id']] : [];
            }
        }
        return $recommends;
    }


    /**
     * 获取额外信息
     * @param $extraId
     * @param $type
     * @return array
     */
    private function getExtraList($extraId, $type)
    {
        switch ($type) {
            case $this->searchVideo:
                $result = Db::table('video_list')->whereIn('id', $extraId)->column("*", "id");
                break;
            case $this->searchTopic:
                $result = Db::table('topic')->whereIn('id', $extraId)->column("*", 'id');
                break;
        }
        return Collection::make($result ?? [])->toArray();
    }

    /**
     * 首页推荐列表
     * @param $page
     * @param $pageSize
     * @param $searchField
     * @param $searchValue
     * @param $status
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recommendList($page, $pageSize, $searchField, $searchValue, $status, $type)
    {
        $list = [];
        $start = ($page - 1) * $pageSize;
        $model = Db::name('recommend')->alias('re')->field('re.*');
        $this->formatLikeSearch($model, $searchField, $searchValue);
        switch ($type) {
            case $this->searchVideo:
                $model->join('video_list vl', 're.src_id=vl.id', 'left')
                    ->where(['vl.delete_time' => $status])
                    ->order('vl.update_time', 'desc');
                break;
            case $this->searchTopic:
                $model->join('topic tp', 're.src_id=tp.id', 'left')
                    ->where(['tp.is_delete' => $status])
                    ->order('tp.update_time', 'desc');
                break;
        }
        $total = $model->count();
        if ($total) {
            $list = $model->limit($start, $pageSize)->select();
            $list = Collection::make($list)->toArray();
            $extraInfo = $this->getExtraList(array_column($list, 'src_id'), $type);
            foreach ($list as $key => $item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['update_time'] = date('Y-m-d H:i:s', $item['update_time']);
                $list[$key]['extra'] = $extraInfo[$item['src_id']] ?? [];
            }
        }
        return ['list' => $list, 'total' => $total];
    }

    public function getList($page, $pageSize, $where = [])
    {
        $start = ($page - 1) * $pageSize;
        $result = RecommendModel::where($where)->limit($start, $pageSize)->order('id', 'desc')->select();
        $count = RecommendModel::where($where)->count();
        $videoTypeIds = [];
        $topicTypeIds = [];

        foreach ($result as $key => $val) {
            if ($val['type'] == 1) {
                array_push($videoTypeIds, $val['src_id']);
            } else if ($val['type'] == 2) {
                array_push($topicTypeIds, $val['src_id']);
            }
        }

        $videos = Db::table('video_list')->whereIn('id', $videoTypeIds)->column("*", "id");
        $topics = Db::table('topic')->whereIn('id', $topicTypeIds)->column("*", 'id');

        foreach ($result as $key => $val) {
            if ($val['type'] == 1) {
                $result[$key]['extra'] = $videos[$val['src_id']] ?? [];
            } elseif ($val['type'] == 2) {
                $result[$key]['extra'] = $topics[$val['src_id']] ?? [];
            }
        }

        return ['list' => $result, 'total' => $count];
    }

    public function create($data)
    {
        $count = Db::table('recommend')->where(['src_id' => $data['src_id'], 'type' => $data['type']])->count();
        if ($count) {
            throw new \Exception("该推荐已经存在");
        }
        return RecommendModel::create($data);
    }

    public function remove($id)
    {
        RecommendModel::destroy($id);
    }
}